
const PORT = 8000;
const { Pool } = require('pg');
const pool = new Pool({
    user: 'postgres',
    host: 'project_data_base',
    //host: '127.0.0.1',
    database: 'postgres',
    password: '1234',
    port: 5432,
  });
class sensor {
     /**
     * @swagger
     * components:
     *   schemas:
     *     Sensor:
     *       type: object
     *       properties:
     *         id:
     *           type: integer
     *         name:
     *           type: string
     *         location:
     *           type: string
     *         min_operating_condition:
     *           type: number
     *         max_operating_condition:
     *           type: number
     *         min_critical_condition:
     *           type: number
     *         max_critical_condition:
     *           type: number
     *         min_fatal_condition:
     *           type: number
     *         max_fatal_condition:
     *           type: number
     *         units:
     *           type: string
     *         frequency:
     *           type: number
     *         on_off:
     *           type: boolean
     *         id_equipment:
     *           type: integer
     * 
     * /sensors:
     *   get:
     *     tags: [Оборудование]
     *     summary: Получение списка сенсоров
     *     parameters:
     *       - in: query
     *         name: limit
     *         schema:
     *           type: integer
     *         description: Количество элементов для возврата
     *       - in: query
     *         name: offset
     *         schema:
     *           type: integer
     *         description: Смещение для получения следующего набора элементов
     *       - in: query
     *         name: equipment
     *         schema:
     *           type: integer
     *         description: Идентификатор оборудования для фильтрации
     *     responses:
     *       200:
     *         description: Список сенсоров
     *         content:
     *           application/json:
     *             schema:
     *               type: object
     *               properties:
     *                 sensors:
     *                   type: array
     *                   items:
     *                     $ref: '#/components/schemas/Sensor'
     *                 next:
     *                   type: string
     *                   nullable: true
     *                 previous:
     *                   type: string
     *                   nullable: true
     *       500:
     *         description: Внутренняя ошибка сервера
     */
    async sensorGet (req, res) {
          try {
            const limit = req.query.limit || 10;
            const offset = req.query.offset || 0;
            const equipment = req.query.equipment || null;
            const values = []
            
            var queryText = `
              SELECT * FROM sensors where 1=1
            `;
            if (equipment !== null) {
              queryText += `AND id_equipment = $1`;
              values.push(equipment)
            }
        
            const result = await pool.query(queryText, values);
            const sensors = result.rows;
         //console.log(sensors)
            const nextOffset =  sensors.length < limit ? 0 : parseInt(offset) + parseInt(limit);
            const previousOffset = parseInt(offset) - parseInt(limit) >= 0 ? parseInt(offset) - parseInt(limit) : null;
        
            const response = {
                sensors,
                next: nextOffset === 0 ? null : `http://localhost:${PORT}/senosors?limit=${limit}&offset=${nextOffset}`,
                previous: previousOffset === null? null : `http://localhost:${PORT}/sensors?limit=${limit}&offset=${previousOffset}`,
            };
        
            res.json(response);
          } catch (error) {
            res.status(500).json({ error: error.message });
          }
        }
    /**
     * @swagger
     * /sensors:
     *   post:
     *     tags: [Оборудование]
     *     summary: Создание нового сенсора
     *     requestBody:
     *       required: true
     *       content:
     *         application/json:
     *           schema:
     *             type: object
     *             properties:
     *               name:
     *                 type: string
     *               location:
     *                 type: string
     *               min_operating_condition:
     *                 type: number
     *               max_operating_condition:
     *                 type: number
     *               min_critical_condition:
     *                 type: number
     *               max_critical_condition:
     *                 type: number
     *               min_fatal_condition:
     *                 type: number
     *               max_fatal_condition:
     *                 type: number
     *               units:
     *                 type: string
     *               frequency:
     *                 type: number
     *               on_off:
     *                 type: boolean
     *               id_equipment:
     *                 type: integer
     *     responses:
     *       200:
     *         description: Новый сенсор создан
     *         content:
     *           application/json:
     *             schema:
     *               $ref: '#/components/schemas/Sensor'
     *       500:
     *         description: Внутренняя ошибка сервера
     */    
    async sensorPost (req, res){
          try {
            const {name, location, min_operating_condition, max_operating_condition, min_critical_condition, max_critical_condition, min_fatal_condition, max_fatal_condition, units, frequency, on_off, id_systems, dimension, comment} = req.body;
        
            const queryText = `
              INSERT INTO sensors (name, location, min_operating_condition, max_operating_condition, min_critical_condition, max_critical_condition, min_fatal_condition, max_fatal_condition, units, frequency, on_off, id_equipment, dimension, comment)
              VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)
              RETURNING *;
            `;
            const values = [name, location, min_operating_condition, max_operating_condition, min_critical_condition, max_critical_condition, min_fatal_condition, max_fatal_condition, units, frequency, on_off, id_systems, dimension === 1?'в час': dimension === 2? 'в день':dimension === 2? 'в неделю': dimension === 4? "в месяц": "в год", comment];
        
            const result = await pool.query(queryText, values);
            const newSensor = result.rows[0];
        
            res.json(newSensor);
          } catch (error) {
            res.status(500).json({ error: error.message });
          }
        }
}

module.exports = new sensor()